import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';
import { Customer } from 'src/app/@core/data/customer';
import { Component, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DialogService, DValidateRules, FormLayout, TableWidthConfig } from 'ng-devui';
import { QuotationItem, SalesQuotation } from 'src/app/@core/data/sale';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { SalesService } from 'src/app/@core/services/sales/sales.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import { SelectCustomerComponent } from 'src/app/@shared/components/select-customer/select-customer.component';
import { SelectMaterialComponent } from 'src/app/@shared/components/select-material/select-material.component';
import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import * as XLSX from 'xlsx';
import { forkJoin, from, switchMap } from 'rxjs';
import { MaterialService } from 'src/app/@core/services/material/material.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-edit-sales-quotation-order',
  templateUrl: './edit-sales-quotation-order.component.html',
  styleUrls: ['./edit-sales-quotation-order.component.scss']
})
export class EditSalesQuotationOrderComponent {
  Math = Math;
  msgs: Array<Object> = [];
  UrlHead:any = environment.modifiedApiUrl
  layoutDirection: FormLayout = FormLayout.Horizontal;
  salesQuotation: SalesQuotation = {
    salesQuotationId: null,
    quotationDate: null,
    customerName: '',
    customerShortName: '',
    customerContact: '',
    contactInfo: '',
    salesmanName: '',
    department: '',
    currency: '',
    remark: '',
    quotationNum: '',
    validDate: null,
    status: '',
    isApprovedPassed: false,
    isClosed: false,
    creationDate: null,
    creator: '',
    files: [],
    fileRemarks: [],
    totalQuantity: 0,
    totalAmountWithTax: 0,
    totalTaxAmount: 0,
    totalDiscountedAmountWithTax: 0,
    totalDiscountedTaxAmount: 0,
    quotationItems: [
      {
        quotationItemId: 0,
        salesQuotationId: 0,
        quotationItemPartId: 0,
        partNum: '',
        pictureUrl: '',
        partName: '',
        partType: '',
        description: '',
        quantity: 0,
        partUOM: '',
        priceWithTax: 0,
        priceWithoutTax: 0,
        taxRate: 0.13,
        discount: 1,
        discountedPriceWithTax: 0,
        amountWithTax: 0,
        amountWithoutTax: 0,
        taxAmount: 0,
        discountedAmountWithTax: 0,
        discountedAmountWithoutTax: 0,
        discountedTaxAmount: 0,
        remark: '',
        transQuantity: 0,
        fujian: ''
      },
    ],
    customerID: undefined,
    customerContactID: undefined
  }
  dataTableOptions = {
    columns: [
      {
        field: 'name',
        header: '物料编码',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '图片',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料名称',
        fieldType: 'text',
      },

      {
        field: 'name',
        header: '规格型号',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料描述',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单位',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单价(含税)',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单价（不含税）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '税率（%）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣（%）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣单价（含税）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '不含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '税额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣不含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣税额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '备注',
        fieldType: 'text',
      },
    ]
  }
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px'
    },
    {
      field: '物料编码',
      width: '200px'
    },
    {
      field: '图片',
      width: '150px'
    },
    {
      field: '物料名称',
      width: '150px'
    },
    {
      field: '规格型号',
      width: '150px'
    },
    {
      field: '物料描述',
      width: '150px'
    },
    {
      field: '数量',
      width: '170px'
    },
    {
      field: '单位',
      width: '150px'
    },
    {
      field: '单价(含税)',
      width: '170px'
    },
    {
      field: '单价（不含税）',
      width: '150px'
    },
    {
      field: '税率（%）',
      width: '170px'
    },
    {
      field: '折扣（%）',
      width: '150px'
    },
    {
      field: '折扣单价（含税）',
      width: '150px'
    },
    {
      field: '含税金额',
      width: '150px'
    },
    {
      field: '不含税金额',
      width: '150px'
    },
    {
      field: '税额',
      width: '150px'
    },
    {
      field: '折扣不含税金额',
      width: '150px'
    },
    {
      field: '折扣含税金额',
      width: '150px'
    },
    {
      field: '折扣税额',
      width: '150px'
    },
    {
      field: '备注',
      width: '150px'
    }
  ];
  salesQuotationRules: { [key: string]: DValidateRules } = {
    quotationNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*销售报价单单号不能为空' },
        { minlength: 2, message: '*销售报价单单号长度至少为2' },
        { maxlength: 40, message: '*销售报价单单号长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*销售报价单单号不能包含空格' }
      ]
    },
    customerName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*客户不能为空' },
      ]
    },
    quotationDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*单据日期不能为空' },
      ]
    },
    partNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料不能为空' },
      ]
    },
    plannedShipmentDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*计划发货时间不能为空' },
      ]
    },
    deliveryDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*计划交货时间不能为空' },
      ]
    },
    priceWithTax: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料单价不能为空' },
      ]
    },
    quantity: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*数量不能为空' },
      ]
    },
    salesmanName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*业务员不能为空' },
      ]
    }
  }
  taxRate: number = 13;
  customerLinkMan: any = [];
  customerContact: any;
  currencyOptions: any[]=[];
  customerData: any;
  constructor(private SalesService: SalesService, private CustomerService: CustomerService, private UserService: UserService, private DialogService: DialogService,private route:ActivatedRoute,private Router:Router,private MaterialService:MaterialService,private ReviewRolesService:ReviewRolesService) { }
  ngOnInit(): void {
    this.route.params.subscribe((params:any)=>{

      if(params.id){
        this.SalesService.GetSalesQuotationById(params.id).subscribe((data:any)=>{
          this.salesQuotation = data;
          this.customerContact = {  customerContactId: data.customerContactID, customerContactName: data.customerContact}
          this.salesQuotation.customerName = data.customerName;
          this.CustomerService.GetCustomerById(data.customerID).subscribe((data: any) => {
            this.customerLinkMan = data.customerContacts;
          })
          this.salesQuotation.quotationDate = new Date(data.quotationDate)
          this.salesQuotation.validDate = data.validDate
          this.salesQuotation.creationDate = data.creationDate
          this.salesQuotation.quotationItems.forEach((item:any)=>{
            item.pictureUrl = item.pictureUrl
            item.fujian = item.fujian || ''
          })

        })
      }
    })
    this.CustomerService.GetPagedCurrency(1,9999).subscribe((data: any) => {
      this.currencyOptions = data.items;
    })
    const userinfoString = localStorage.getItem('userinfo');
    if (userinfoString) {
      this.salesQuotation.creator = JSON.parse(userinfoString).username;
    }
  }
  selectCustomer(dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: "",
      title: '选择客户',
      content: SelectCustomerComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {

            this.customerData = results.modalContentInstance.selectData
            this.salesQuotation.customerName = results.modalContentInstance.selectData.chineseName;
            this.salesQuotation.customerShortName = results.modalContentInstance.selectData.customerAbbreviation;
            this.customerLinkMan = results.modalContentInstance.selectData.customerContacts;
            this.salesQuotation.currency = results.modalContentInstance.selectData.currency;
            this.UserService.GetUserById(results.modalContentInstance.selectData.salesmanId).subscribe((data: any) => {
              this.salesQuotation.salesmanName = data.name;
              this.UserService.GetDepartmentById(data.departmentId).subscribe((data: any) => {
                this.salesQuotation.department = data.name;
              })
            })
            this.salesQuotation.quotationItems.forEach(
              (item:any)=>{
                this.calculateAmount(item)
              }
            )
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectUser(dialogtype?: string){
    if(this.salesQuotation.customerName != ""){
      const results = this.DialogService.open({
        id: 'Add',
        maxHeight: '400px',
        width: '800px',
        backdropCloseable: true,
        data: "",
        title: '选择业务员',
        content: SelectUserComponent,
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {

              this.salesQuotation.salesmanName = results.modalContentInstance.selectData.name;
              this.UserService.GetDepartmentById(results.modalContentInstance.selectData.departmentId).subscribe((data: any) => {
                this.salesQuotation.department = data.name;
              })
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }else{
      this.showToast('error','错误','请先选择客户')
    }
  }
  slectLinkMan(event: any) {
    this.CustomerService.GetCustomerContactById(event).subscribe((data: any) => {

      this.salesQuotation.customerContact = data.customerContactName
      this.salesQuotation.customerContactID = data.customerContactId
      this.salesQuotation.contactInfo = data.phone
    })
  }
  selectMaterial(rowItem:any,dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: "",
      title: '选择物料',
      content: SelectMaterialComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {

            rowItem.partNum = results.modalContentInstance.selectData.partNum;
            rowItem.quotationItemPartId=results.modalContentInstance.selectData.partId;
            rowItem.pictureUrl = results.modalContentInstance.selectData.fileURL;
            rowItem.partName = results.modalContentInstance.selectData.partName;
            rowItem.partType = results.modalContentInstance.selectData.partType;
            rowItem.description = results.modalContentInstance.selectData.description;
            rowItem.partUOM = results.modalContentInstance.selectData.partUOM;
            rowItem.priceWithTax = results.modalContentInstance.selectData.salePrice || 0;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  addRow() {
    this.salesQuotation.quotationItems.push({
      quotationItemId: 0,
      salesQuotationId: 0,
      quotationItemPartId: 0,
      partNum: '',
      pictureUrl: '',
      partName: '',
      partType: '',
      description: '',
      quantity: 0,
      partUOM: '',
      priceWithTax: 0,
      priceWithoutTax: 0,
      taxRate: 0.13,
      discount: 1,
      discountedPriceWithTax: 0,
      amountWithTax: 0,
      amountWithoutTax: 0,
      taxAmount: 0,
      discountedAmountWithTax: 0,
      discountedAmountWithoutTax: 0,
      discountedTaxAmount: 0,
      remark: '',
      transQuantity: 0,
      fujian: ''
    });
  }//添加行
  deleteRow(index: number) {
    this.salesQuotation.quotationItems.splice(index, 1);
    this.calculateTotal();
  }//删除行
  taxRateChange(rowitem: any, value: number) {
    rowitem.taxRate = value / 100;
    this.calculateAmount(rowitem);
    this.calculateTotal();
  }//税率改变
  quantityChange(rowitem: any) {
    this.calculateAmount(rowitem)
    this.calculateTotal()
  }//数量改变
  priceWithTaxChange(rowitem: any) {
    this.calculateAmount(rowitem)
    this.calculateTotal()
  }//含税单价改变
  discountChange(rowitem: any, value: number) {
    rowitem.discount = value / 100;
    this.calculateAmount(rowitem)
    this.calculateTotal()
  }//折扣改变
  calculateAmount(item: {
    discountedPriceWithTax: number;
    priceWithTax: number;
    taxRate: number;
    amountWithoutTax: number;
    quantity: number;
    priceWithoutTax: number;
    taxAmount: number;
    amountWithTax: number; // 更改类型为number
    discountedAmountWithoutTax: number;
    discount: number;
    discountedTaxAmount: number;
    discountedAmountWithTax: number; // 更改类型为number
  }): void {
    //计算不含税单价，并保留6位小数
    item.priceWithoutTax = +(item.priceWithTax / (1 + item.taxRate)).toFixed(4);
    item.amountWithTax = +(item.priceWithTax*item.quantity).toFixed(4);
    item.taxAmount = +((item.priceWithTax - item.priceWithoutTax)*item.quantity).toFixed(4);
    item.amountWithoutTax = +(item.amountWithTax - item.taxAmount).toFixed(4);
    item.discountedPriceWithTax = +(item.priceWithTax * item.discount).toFixed(4);
    item.discountedTaxAmount = +(item.taxAmount * item.discount).toFixed(4);
    item.discountedAmountWithTax = +(item.discountedPriceWithTax * item.quantity).toFixed(4);
    item.discountedAmountWithoutTax = +(item.discountedAmountWithTax - item.discountedTaxAmount).toFixed(4);
    this.calculateTotal()
  }
  calculateTotal() {
    this.salesQuotation.totalQuantity = this.salesQuotation.quotationItems.reduce((acc, cur) => acc + cur.quantity, 0);//数量
    this.salesQuotation.totalAmountWithTax = this.salesQuotation.quotationItems.reduce((acc, cur) => acc + cur.amountWithTax, 0);//含税金额
    this.salesQuotation.totalTaxAmount = this.salesQuotation.quotationItems.reduce((acc, cur) => acc + cur.taxAmount, 0);//税额
    this.salesQuotation.totalDiscountedAmountWithTax = this.salesQuotation.quotationItems.reduce((acc, cur) => acc + cur.discountedAmountWithTax, 0);//折扣含税金额
    this.salesQuotation.totalDiscountedTaxAmount = this.salesQuotation.quotationItems.reduce((acc, cur) => acc + cur.discountedTaxAmount, 0);//折扣税额
  }//计算总金额
  isStartApproval: boolean = false
  isStartApprovalChange() {
    this.isStartApproval = true
  }
  submit($event:any){
    this.salesQuotation.creationDate = new Date()

    if($event.valid){
      if(this.validateSalesQuotation(this.salesQuotation)){
        console.log(this.salesQuotation)
    this.SalesService.UpdateSalesQuotation(this.salesQuotation.salesQuotationId,this.salesQuotation).subscribe((data:any)=>{
      if(this.isStartApproval){
        this.ReviewRolesService.StartApprovalFlow('销售报价单审核流配置',[this.salesQuotation.quotationNum]).subscribe((data:any)=>{
          this.showToast('success','成功','提交成功')
          setTimeout(() => {
            this.Router.navigateByUrl('/pages/sales-master/sales-quotation-order')
          }, 1000);
        },error=>{
          this.showToast('error', '错误', '单据更新成功，审批流程启动失败');
            setTimeout(() => {
              this.Router.navigateByUrl('/pages/sales-master/sales-quotation-order')
            }, 1000);
        }
      )
      }else{
        this.showToast('success','成功','提交成功')
        setTimeout(() => {
          this.Router.navigateByUrl('/pages/sales-master/sales-quotation-order')
        }, 1000);
      }
    },(error: any) => {
      if (error.status === 404) {
        this.showToast('error', '错误', '网络连接错误');
      } else {
        this.showToast('error', '错误', error.error);
      }
    }
  )}}
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl + url);
    return urls;
  }
  cancel(){
    this.Router.navigateByUrl('/pages/sales-master/sales-quotation-order')
  }
  fujian(dialogtype?:string) {
    const results = this.DialogService.open({
      title: '销售附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '销售附件',
        urls:  this.salesQuotation.files
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.salesQuotation.files.push(results.modalContentInstance.urls)

            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  writeExcel() {
    const headers = ['物料编号', '数量', '单价', '税率', '备注'];
    const ws = XLSX.utils.aoa_to_sheet([headers]);
    const redFontStyle = { font: { color: { rgb: "#FF0000" } } };
    ws['A1'].s = redFontStyle;
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    XLSX.writeFile(wb, '销售报价单物料.xlsx');
  }
  mappedRows: QuotationItem[] = []
  readExcel(file: any) {
    const reader = new FileReader();
    reader.onload = (e: any) => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });
      // 假设我们只处理第一个工作表
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      // 将工作表转换为JSON
      const json = XLSX.utils.sheet_to_json(worksheet);

      const observables = json.map((item: any) => {
        return from(this.MaterialService.getParts(null, null, item['物料编号'])).pipe(
          switchMap((data: any) => {
            item.partData = data.items[0];
            return [item]; // 将结果包装在数组中，以便与 forkJoin 的结果格式保持一致
          })
        );
      });
      forkJoin(observables).subscribe((data: any) => {
        this.mappedRows = json.map(row => ({
          quotationItemId: 0,
          salesQuotationId: 0,
          quotationItemPartId: 0,
          partNum: row['物料编号']|| '',
          pictureUrl: row['partData'].fileURL|| '',
          partName: row['partData'].partName|| '',
          partType: row['partData'].partType|| '',
          description: '',
          quantity: row['数量']|| '',
          partUOM: row['partData'].partUOM,
          priceWithTax: row['单价']|| '',
          priceWithoutTax: 0,
          taxRate: row['税率'] || this.customerData?.taxRate || 0,
          discount: this.customerData?.customerDiscountDiscount || 1,
          discountedPriceWithTax: 0,
          amountWithTax: 0,
          amountWithoutTax: 0,
          taxAmount: 0,
          discountedAmountWithTax: 0,
          discountedAmountWithoutTax: 0,
          discountedTaxAmount: 0,
          remark: row['备注']|| '',
          transQuantity: 0,
          fujian: row['partData'].addFileURL|| ''
        }));
        this.salesQuotation.quotationItems = this.salesQuotation.quotationItems.filter(item => item.partNum !== '')
        // 然后将新的行（mappedRows）添加到数组中
        this.mappedRows.forEach(row=>this.calculateAmount(row));
        this.salesQuotation.quotationItems.push(... this.mappedRows)
        this.calculateTotal()
      })
      // 先过滤掉 partNum 为空字符串的对象
    };
    reader.readAsArrayBuffer(file);
  }
  loadFujian(){
    this.salesQuotation.files = [
      ...this.salesQuotation.files,
      ...this.salesQuotation.quotationItems
        .map(item => item.fujian.split(','))
        .flat()
        .filter(item => item)
    ];
  }
  @ViewChild('fileInput') fileInput: any;
  onButtonClick() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput.nativeElement.click();
  }
  onFileChange(event: any) {
    const file = event.target.files[0]; // 获取选中的文件
    if (file) {
      this.readExcel(file); // 调用readExcel方法并传递文件对象
      event.target.value = '';
    }
  }
  validateSalesQuotation(salesQuotation: SalesQuotation): boolean {
    // 验证基本信息
    if (!salesQuotation.quotationDate) {
      this.showToast('error', '错误', '报价日期不能为空');
      return false;
    }
    if (!salesQuotation.quotationNum) {
      this.showToast('error', '错误', '销售报价单单号不能为空');
      return false;
    }
    if (!salesQuotation.customerName) {
      this.showToast('error', '错误', '客户名称不能为空');
      return false;
    }
    // 验证 quotationItems 数组
    for (const [index, item] of salesQuotation.quotationItems.entries()) {
      if (!item.partNum) {
        this.showToast('error', '错误', `第${index + 1}行物料编码不能为空`);
        return false;
      }
      if (item.quantity <= 0) {
        this.showToast('error', '错误', `第${index + 1}行数量必须大于0`);
        return false;
      }
      if (item.priceWithTax <= 0) {
        this.showToast('error', '错误', `第${index + 1}行单价(含税)必须大于0`);
        return false;
      }
    }
    // 所有验证通过
    return true;
  }
  uploadSaleOrderPartsFromExcel(event: any) {
    const fileInput = event.target;
    const file = event.target.files[0];
    this.SalesService.uploadSaleOrderPartsFromExcel(file).subscribe((res: any) => {
      res.map((item:any) => {
        item.taxRate = this.customerData?.taxRate || 0,
        item.discount = this.customerData?.customerDiscountDiscount || 1,
        item.fujian = item.addFileURL
      })
      this.salesQuotation.quotationItems = this.salesQuotation.quotationItems.filter(item => item.partNum !== '').concat(res);
      this.salesQuotation.quotationItems.map((item) => {
        this.MaterialService.getPartById(item.quotationItemPartId).subscribe((data: any) => {
          item.fujian = data.addFileURL
        })
      })
      this.salesQuotation.quotationItems.map((item) => {
        this.calculateAmount(item)
      })
      this.showToast('success', '成功', '上传成功')
      this.calculateTotal()
      fileInput.value = '';
    }, error => {
      // 如果发生错误也重置，确保用户可以重新尝试上传
      this.showToast('error', '错误', error.error)
      fileInput.value = '';
    })
  }
}
